package cn.dkk.create_design.singleton.destroy;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * 防止破坏单例模式
 */
public class InDestroySingleton {

    public static void main(String[] args) throws Exception {
        Class<StaticBlockHungerSingleton> clazz = StaticBlockHungerSingleton.class;
        Constructor<StaticBlockHungerSingleton> constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
//        StaticBlockHungerSingleton singleton = constructor.newInstance();
//        StaticBlockHungerSingleton singleton1 = constructor.newInstance();
        StaticBlockHungerSingleton singleton = StaticBlockHungerSingleton.getSingleton();
        StaticBlockHungerSingleton singleton1 = StaticBlockHungerSingleton.getSingleton();
        System.out.println(singleton==singleton1);
        // writeObjectToFile();
        // System.out.println(readObjectFromFile()==readObjectFromFile());
    }

    public static void writeObjectToFile() throws Exception{
        StaticBlockHungerSingleton singleton = StaticBlockHungerSingleton.getSingleton();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("C:\\Users\\DKK\\Desktop\\1.txt"));
        objectOutputStream.writeObject(singleton);
        objectOutputStream.close();
    }

    public static Object readObjectFromFile() throws Exception{
        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("C:\\Users\\DKK\\Desktop\\1.txt"));
        return inputStream.readObject();
    }

}
class StaticBlockHungerSingleton implements Serializable {

    private static StaticBlockHungerSingleton singleton;

    static {
        singleton = new StaticBlockHungerSingleton();
    }

    private StaticBlockHungerSingleton() {
        synchronized (StaticBlockHungerSingleton.class) {
            if (singleton != null) {
                throw new RuntimeException("无法通过无参构造创建对象");
            }
        }
    }

    public static StaticBlockHungerSingleton getSingleton(){
        return singleton;
    }

    /**
     * 通过java官方定义的反序列化钩子函数防止单例模式被破坏
     */
    public Object readResolve(){
        System.out.println("反序列化钩子函数被调用");
        return singleton;
    }

}


